<template>
  <div class="news-detail-page">
    <div class="page-container" v-loading="loading">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="$router.back()" :icon="ArrowLeft">
          返回列表
        </el-button>
      </div>

      <!-- 资讯详情 -->
      <div class="news-detail" v-if="newsDetail">
        <!-- 头部信息 -->
        <div class="detail-header">
          <div class="header-image">
            <img :src="newsDetail.coverImage || '/default-news.jpg'" :alt="newsDetail.title" />
            <div class="image-overlay">
              <div class="news-type" :class="`type-${newsDetail.type}`">
                {{ getTypeText(newsDetail.type) }}
              </div>
              <div class="top-badge" v-if="newsDetail.isTop">
                <el-icon><Top /></el-icon>
                置顶
              </div>
              <div class="recommend-badge" v-if="newsDetail.isRecommend">
                <el-icon><Star /></el-icon>
                推荐
              </div>
            </div>
          </div>

          <div class="header-content">
            <h1>{{ newsDetail.title }}</h1>
            <p class="subtitle" v-if="newsDetail.subtitle">{{ newsDetail.subtitle }}</p>
            <p class="summary">{{ newsDetail.summary }}</p>

            <!-- 元信息 -->
            <div class="meta-info">
              <div class="meta-row">
                <div class="meta-item" v-if="newsDetail.author">
                  <el-icon><User /></el-icon>
                  <span>{{ newsDetail.author }}</span>
                </div>
                <div class="meta-item" v-if="newsDetail.source">
                  <el-icon><Document /></el-icon>
                  <span>{{ newsDetail.source }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDate(newsDetail.publishTime || newsDetail.createTime) }}</span>
                </div>
              </div>

              <!-- 活动信息 -->
              <div class="event-info" v-if="newsDetail.type === 1 && (newsDetail.eventStartTime || newsDetail.eventLocation)">
                <h4><el-icon><Calendar /></el-icon> 活动信息</h4>
                <div class="event-details">
                  <div class="event-item" v-if="newsDetail.eventStartTime">
                    <span class="label">活动时间:</span>
                    <span class="value">{{ formatEventTime(newsDetail.eventStartTime, newsDetail.eventEndTime) }}</span>
                  </div>
                  <div class="event-item" v-if="newsDetail.eventLocation">
                    <span class="label">活动地点:</span>
                    <span class="value">{{ newsDetail.eventLocation }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 统计信息 -->
            <div class="stats-row">
              <div class="stat-item">
                <el-icon><View /></el-icon>
                <span>{{ newsDetail.viewCount }} 浏览</span>
              </div>
              <div class="stat-item">
                <el-icon><StarFilled /></el-icon>
                <span>{{ newsDetail.likeCount }} 点赞</span>
              </div>
              <div class="stat-item">
                <el-icon><Share /></el-icon>
                <span>{{ newsDetail.shareCount }} 分享</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button
                :icon="StarFilled"
                @click="handleLike"
                :loading="likeLoading"
                :class="{ 'is-liked': isLiked }"
              >
                {{ isLiked ? '已点赞' : '点赞' }}
              </el-button>
              <el-button
                :icon="Collection"
                @click="handleFavorite"
                :loading="favoriteLoading"
                :class="{ 'is-favorited': isFavorited }"
              >
                {{ isFavorited ? '已收藏' : '收藏' }}
              </el-button>
              <el-button
                :icon="Share"
                @click="handleShare"
              >
                分享
              </el-button>
              <el-button
                v-if="newsDetail.type === 1"
                type="primary"
                :icon="Calendar"
                @click="addToCalendar"
              >
                添加到日历
              </el-button>
            </div>

            <!-- 标签 -->
            <div class="tags-section" v-if="newsDetail.tags">
              <div class="tags">
                <el-tag
                  v-for="tag in getTags(newsDetail.tags)"
                  :key="tag"
                  size="small"
                  @click="searchByTag(tag)"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 详细内容 -->
        <div class="detail-content">
          <div class="content-section">
            <h2>详细内容</h2>
            <div class="content-text" v-html="newsDetail.content"></div>
          </div>
        </div>

        <!-- 相关推荐 -->
        <div class="related-section" v-if="relatedList.length > 0">
          <div class="section-header">
            <h2><el-icon><Connection /></el-icon> 相关资讯</h2>
          </div>
          <div class="related-grid">
            <div
              v-for="item in relatedList"
              :key="item.id"
              class="related-item"
              @click="goToDetail(item.id)"
            >
              <div class="item-image">
                <img :src="item.coverImage || '/default-news.jpg'" :alt="item.title" />
                <div class="news-type" :class="`type-${item.type}`">
                  {{ getTypeText(item.type) }}
                </div>
              </div>
              <div class="item-content">
                <h4>{{ item.title }}</h4>
                <p>{{ item.summary }}</p>
                <div class="item-meta">
                  <span class="item-time">{{ formatDate(item.publishTime || item.createTime) }}</span>
                  <div class="item-stats">
                    <span><el-icon><View /></el-icon> {{ item.viewCount }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载失败 -->
      <div class="error-state" v-if="error">
        <el-result
          icon="error"
          title="加载失败"
          sub-title="无法获取资讯详情，请稍后重试"
        >
          <template #extra>
            <el-button type="primary" @click="fetchDetail">重新加载</el-button>
            <el-button @click="$router.back()">返回列表</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, Top, Star, User, Document, Clock, Calendar, View, Share, StarFilled,
  Collection, Connection
} from '@element-plus/icons-vue'
import { newsApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { News } from '@/types/common'
import { NEWS_TYPES } from '@/types/common'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const error = ref(false)
const newsDetail = ref<News | null>(null)
const relatedList = ref<News[]>([])
const interactionStatus = ref<any>({})

// 交互状态
const likeLoading = ref(false)
const favoriteLoading = ref(false)
const isLiked = computed(() => interactionStatus.value.liked || false)
const isFavorited = computed(() => interactionStatus.value.favorited || false)

// 获取详情ID
const detailId = computed(() => Number(route.params.id))

// 获取资讯详情
const fetchDetail = async () => {
  if (!detailId.value) return

  loading.value = true
  error.value = false

  try {
    const response = await newsApi.getNewsDetail(detailId.value)
    newsDetail.value = response.data

    // 获取相关资讯
    try {
      const relatedResponse = await newsApi.getNewsPage({
        page: 1,
        size: 6,
        type: newsDetail.value.type
      })
      relatedList.value = relatedResponse.data.list.filter(item => item.id !== detailId.value)
    } catch (err) {
      console.error('获取相关资讯失败:', err)
    }

    // TODO: 如果用户已登录，获取交互状态
    if (userStore.isLoggedIn) {
      try {
        // const statusResponse = await newsApi.getInteractionStatus(detailId.value)
        // interactionStatus.value = statusResponse.data
      } catch (err) {
        console.error('获取交互状态失败:', err)
      }
    }

  } catch (err) {
    console.error('获取资讯详情失败:', err)
    error.value = true
    ElMessage.error('获取资讯详情失败')
  } finally {
    loading.value = false
  }
}

// 点赞操作
const handleLike = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  likeLoading.value = true
  try {
    // TODO: 实现点赞 API
    ElMessage.success('点赞成功')
    if (newsDetail.value) {
      newsDetail.value.likeCount++
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    likeLoading.value = false
  }
}

// 收藏操作
const handleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  favoriteLoading.value = true
  try {
    // TODO: 实现收藏 API
    ElMessage.success('收藏成功')
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    favoriteLoading.value = false
  }
}

// 分享操作
const handleShare = async () => {
  try {
    if (navigator.share) {
      await navigator.share({
        title: newsDetail.value?.title,
        text: newsDetail.value?.summary,
        url: window.location.href
      })
    } else {
      await navigator.clipboard.writeText(window.location.href)
      ElMessage.success('链接已复制到剪贴板')
    }

    if (newsDetail.value) {
      newsDetail.value.shareCount++
    }
  } catch (error) {
    if (error instanceof Error && error.name !== 'AbortError') {
      ElMessage.error('分享失败')
    }
  }
}

// 添加到日历
const addToCalendar = () => {
  if (!newsDetail.value || !newsDetail.value.eventStartTime) {
    ElMessage.warning('暂无活动时间信息')
    return
  }

  const startTime = new Date(newsDetail.value.eventStartTime)
  const endTime = newsDetail.value.eventEndTime ? new Date(newsDetail.value.eventEndTime) : new Date(startTime.getTime() + 2 * 60 * 60 * 1000) // 默认2小时

  const formatDateTime = (date: Date) => {
    return date.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z'
  }

  const details = [
    newsDetail.value.title,
    newsDetail.value.summary,
    newsDetail.value.eventLocation ? `地点: ${newsDetail.value.eventLocation}` : ''
  ].filter(Boolean).join('\n')

  const calendarUrl = [
    'https://calendar.google.com/calendar/render?action=TEMPLATE',
    `text=${encodeURIComponent(newsDetail.value.title)}`,
    `dates=${formatDateTime(startTime)}/${formatDateTime(endTime)}`,
    `details=${encodeURIComponent(details)}`,
    newsDetail.value.eventLocation ? `location=${encodeURIComponent(newsDetail.value.eventLocation)}` : ''
  ].filter(Boolean).join('&')

  window.open(calendarUrl, '_blank')
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/news/${id}`)
}

// 按标签搜索
const searchByTag = (tag: string) => {
  router.push({
    path: '/search',
    query: { keyword: tag, tab: 'news' }
  })
}

// 获取类型文本
const getTypeText = (type: number) => {
  return NEWS_TYPES[type as keyof typeof NEWS_TYPES] || '其他'
}

// 获取标签数组
const getTags = (tagsString: string) => {
  return tagsString ? tagsString.split(',').filter(tag => tag.trim()) : []
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 格式化活动时间
const formatEventTime = (startTime: string, endTime?: string) => {
  const start = new Date(startTime)
  const startStr = start.toLocaleString('zh-CN')

  if (endTime) {
    const end = new Date(endTime)
    const endStr = end.toLocaleString('zh-CN')

    const startDate = start.toDateString()
    const endDate = end.toDateString()

    if (startDate === endDate) {
      // 同一天
      return `${start.toLocaleDateString('zh-CN')} ${start.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })} - ${end.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
    } else {
      // 不同天
      return `${startStr} - ${endStr}`
    }
  }

  return startStr
}

onMounted(() => {
  fetchDetail()
})

// 监听路由变化，重新获取详情
watch(() => route.params.id, (newId) => {
  if (newId && newId !== String(detailId.value)) {
    fetchDetail()
  }
})
</script>

<style scoped>
.news-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.news-detail {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 头部信息 */
.detail-header {
  position: relative;
}

.header-image {
  position: relative;
  height: 300px;
  overflow: hidden;
}

.header-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.news-type {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  color: #fff;
}

.news-type.type-1 {
  background: #2196f3;
}

.news-type.type-2 {
  background: #4caf50;
}

.news-type.type-3 {
  background: #ff9800;
}

.top-badge,
.recommend-badge {
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 4px;
}

.top-badge {
  background: linear-gradient(135deg, #ff9800, #ffc107);
}

.recommend-badge {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
}

.header-content {
  padding: 32px;
}

.header-content h1 {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.3;
}

.subtitle {
  font-size: 18px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
}

.summary {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 24px;
}

/* 元信息 */
.meta-info {
  margin-bottom: 24px;
}

.meta-row {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.meta-item .el-icon {
  font-size: 16px;
  color: #999;
}

/* 活动信息 */
.event-info {
  background: #f0f8ff;
  border: 1px solid #e3f2fd;
  border-radius: 8px;
  padding: 20px;
}

.event-info h4 {
  font-size: 16px;
  color: #2196f3;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.event-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.event-item {
  display: flex;
  font-size: 14px;
}

.event-item .label {
  color: #666;
  min-width: 80px;
  font-weight: 500;
}

.event-item .value {
  color: #333;
  flex: 1;
}

.stats-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.stat-item .el-icon {
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
  flex-wrap: wrap;
}

.action-buttons .el-button.is-liked {
  background: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

.action-buttons .el-button.is-favorited {
  background: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
}

.tags-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tags .el-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.tags .el-tag:hover {
  background: #2196f3;
  color: #fff;
  border-color: #2196f3;
}

/* 详细内容 */
.detail-content {
  padding: 32px;
  border-top: 1px solid #f0f0f0;
}

.content-section h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #2196f3;
  display: inline-block;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.content-text :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.content-text :deep(p) {
  margin-bottom: 16px;
}

.content-text :deep(h1),
.content-text :deep(h2),
.content-text :deep(h3),
.content-text :deep(h4),
.content-text :deep(h5),
.content-text :deep(h6) {
  margin: 24px 0 16px;
  color: #333;
  font-weight: bold;
}

.content-text :deep(ul),
.content-text :deep(ol) {
  padding-left: 24px;
  margin-bottom: 16px;
}

.content-text :deep(li) {
  margin-bottom: 8px;
}

/* 相关推荐 */
.related-section {
  padding: 32px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.section-header h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.related-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.related-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.item-image {
  position: relative;
  height: 120px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.related-item:hover .item-image img {
  transform: scale(1.05);
}

.item-content {
  padding: 16px;
}

.item-content h4 {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-content p {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.item-stats span {
  display: flex;
  align-items: center;
  gap: 2px;
}

.error-state {
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .header-content {
    padding: 24px 20px;
  }

  .header-content h1 {
    font-size: 24px;
  }

  .meta-row {
    flex-direction: column;
    gap: 8px;
  }

  .stats-row {
    flex-wrap: wrap;
    gap: 16px;
  }

  .action-buttons {
    justify-content: center;
  }

  .detail-content {
    padding: 24px 20px;
  }

  .related-section {
    padding: 24px 20px;
  }

  .related-grid {
    grid-template-columns: 1fr;
  }

  .event-details {
    gap: 12px;
  }

  .event-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .event-item .label {
    min-width: auto;
    margin-bottom: 2px;
  }
}
</style>
